<?php

namespace App\Http\Controllers\Api\V2;

use Illuminate\Http\Request;
use App\Modules\EntMemberInfo;
use App\Modules\EntReadingParty;

use App\Modules\EntSumupReply;
use App\Modules\EntCommZanLog;
use App\Modules\EntCommentReply;

use Illuminate\Support\Facades\Storage;
use Validator, DB;

use App\Models\V1\MemberModel;
use App\Common\Jpush;
use App\Common\ApiData;
use App\Models\V1\MessageModel;
use App\Models\V1\BookModel;
use App\Models\V1\ReadPartyModel;
use App\Models\V1\CompanyModel;

class ReadingPartyController extends BaseController
{

    protected $url;
    protected $urlapi;
    protected $fileTypes = array('jpg', 'jpeg', 'png');
    protected $isReaParID = 0;


    public function __construct()
    {
        $this->url    = env('ADMIN_HOST');
        $this->urlapi = env('API_HOST');
    }

    /*========= 1.读书会首页  读书详情页 =============*/
    /**
     * 读书会首页
     *
     * */
    public function read_party_index(Request $request)
    {
        $readPartyModel = new ReadPartyModel();
        $apiData        = new ApiData();
        //1.头部广告
        $hotAds = $readPartyModel->get_read_party_ad();
        $apiData->set_data('hotslist', $hotAds);

        //2.会员的读书会
        $mobile      = $request->input('mobile');
        $appKey      = $request->input('key');
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $appKey);
        $readPartys  = [];

        if ($memberInfo == false) {

            $apiData->code    = '3009';
            $apiData->message = '重新登录！';
            $apiData->set_data('homegrouplist', $readPartys);
            return $apiData->send_old();
        }


        $readPartys = $readPartyModel->get_member_read_party($memberInfo->UserID);
        foreach ($readPartys as $par) {
            $par->Description = "";
            $readPartyId      = $par->ReaParID;
            //获取该读书会的成员数量
            $memberCount = $readPartyModel->count_read_party_number($readPartyId);
            $par->msun   = $memberCount;

            //查询该读书会的今日动态 实际上就是有多少人写了读书日志
            $countReadPlan = $readPartyModel->count_read_party_member_read_plan($readPartyId);
            $par->usum     = $countReadPlan;


            $states     = ['审核中', '审核通过', '审核失败'];    //0：审核中 1:审核通过 2:审核失败
            $par->sname = $states[$par->States];


            $tnames     = ['', '企业', '个人', '官方'];          //1,企业，2，个人，3，官方
            $par->tname = $tnames[$par->ReaParType];

            $par->isadmin = $par->MemNumber == $memberInfo->MemNumber ? "1" : "0";
        }

        $apiData->code    = '200';
        $apiData->message = '0k';
        $apiData->set_data('homegrouplist', $readPartys);
        return $apiData->send_old();
    }

    /**
     * 读书会详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function read_party_detail(Request $request)
    {
        $apiData = new ApiData();
        $book    = $request->input('book', 0);
        $readId  = $request->input('id');
        $mobile  = $request->input('mobile');
        $key     = $request->input('key');
        $params  = [
            'mobile' => [$mobile, "缺少手机号", "2037"],
            'key' => [$key, "缺少设备ID", "2038"],
            'readId' => [$readId, "缺少读书会ID", "2039"]
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }

        //读取读书会
        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readId);
        if (!$readPartyInfo) { //读书会信息不存在
            $apiData->message = "读书会不存在";
            $apiData->code    = "3062";
            return $apiData->send();
        }


        $bookModel = new BookModel();
        //读取最新书籍
        if ($book > 0) {
            $bookInfo = $bookModel->get_book_info($book);
        }
        if ($book == 0 || (!$bookInfo)) {
            $bookInfo = $bookModel->get_last_book_info();
        }
        $bookInfo->bookurl = $bookInfo->FilePath1;


        //验证是否有修改头像权限 1-是 0-否
        $isAdmin          = $memberInfo->MemNumber == $readPartyInfo->MemNumber ? 1 : 0;
        $readPartyMembers = $readPartyModel->get_read_party_member($readId); //读取读书会前6位成员

        //读书会的信息
        $arrayReadingParty = [
            'id' => $bookInfo->BookID,
            'bookurl' => $bookInfo->FilePath1,
            'bookname' => $bookInfo->BookTitle,
            'bookdescription' => $bookInfo->BookDesc,
            'time' => $bookInfo->ReleaseDate,
            'groupid' => $readId,
            'groupurl1' => $readPartyInfo->FilePath1,
            'groupurl2' => $readPartyInfo->FilePath2,
            'groupname' => $readPartyInfo->ReaParName,
            'isadmin' => $isAdmin
        ];


        //读书改进计划
        $bookSumup = $bookModel->get_read_plan_by_book_readparty($bookInfo->BookID, $readId);

        foreach ($bookSumup as $data) {
            $commentId         = $data->SumUpID;
            $data->zan         = $readPartyModel->get_read_plan_money_gift($commentId, $readId);     //取出打赏记录
            $data->commentlist = $readPartyModel->get_read_plan_comment($commentId, $readId); //评论
        }

        $memberMoney   = $readPartyModel->get_member_money($memberInfo->MemNumber, $readId);        //登录者获得的金币
        $totalOutMoeny = $readPartyModel->get_total_out_money($memberInfo->MemNumber, $readId);   //登录者打赏出去的金币


        $apiData->set_data('memberMoney', $memberMoney)
            ->set_data('outMoney', $totalOutMoeny)
            ->set_data('ruledetail', $readPartyInfo->Regulation)
            ->set_data('bookplanlist', $bookSumup)
            ->set_data('readingdetail', $arrayReadingParty)
            ->set_data('memberlist', $readPartyMembers);
        return $apiData->send_old();
    }

    public function read_party_detail_v3(Request $request)
    {
        $apiData = new ApiData();
        $book    = $request->input('book', 0);
        $readId  = $request->input('id');
        $mobile  = $request->input('mobile');
        $key     = $request->input('key');
        $params  = [
            'mobile' => [$mobile, "缺少手机号", "2037"],
            'key' => [$key, "缺少设备ID", "2038"],
            'readId' => [$readId, "缺少读书会ID", "2039"]
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }


        //读取读书会
        $readPartyModel = new ReadPartyModel();


        $readPartyInfo = $readPartyModel->get_read_party_info($readId);
        if (!$readPartyInfo) { //读书会信息不存在
            $apiData->message = "读书会不存在";
            $apiData->code    = "3062";
            return $apiData->send();
        }
        $userReadInfo = $readPartyModel->get_read_party_member_detail($memberInfo->UserID, $readId);
        if (!$userReadInfo) {
            $apiData->message = "您没有参加该读书会";
            $apiData->code    = "3063";
            return $apiData->send();
        }
        $readPartyInfo->isEmployee  = $userReadInfo->is_employee;
        $readPartyInfo->rewardRight = $userReadInfo->reward_right;

        $bookModel = new BookModel();
        //读取最新书籍
        if ($book > 0) {
            $bookInfo = $bookModel->get_book_info($book);
        }
        if ($book == 0 || (!$bookInfo)) {
            $bookInfo = $bookModel->get_last_book_info();
        }
        $bookInfo->bookurl = $bookInfo->FilePath1;


        //验证是否有修改头像权限 1-是 0-否
        $isAdmin                = $memberInfo->MemNumber == $readPartyInfo->MemNumber ? 1 : 0;
        $readPartyInfo->isAdmin = $isAdmin;

        $frontMembers = $readPartyModel->get_read_party_member($readId, '', 6); //读取读书会前6位成员  注意 读取6个会员

        //读书会的信息
        $arrayReadingParty = [
            'id' => $bookInfo->BookID,
            'bookurl' => $bookInfo->FilePath1,
            'bookname' => $bookInfo->BookTitle,
            'bookdescription' => $bookInfo->BookDesc,
            'time' => $bookInfo->ReleaseDate,
            'groupid' => $readId,
            'groupurl1' => $readPartyInfo->FilePath1,
            'groupurl2' => $readPartyInfo->FilePath2,
            'groupname' => $readPartyInfo->ReaParName,
            'isadmin' => $isAdmin
        ];


        //读书改进计划
        if($readPartyInfo->ReaParType == 2){
            $bookSumup = $bookModel->get_read_plan_by_book_readparty_v2($bookInfo->BookID, $readId,-1,2);
        }else{
            $bookSumup = $bookModel->get_read_plan_by_book_readparty_v2($bookInfo->BookID, $readId);
        }


        foreach ($bookSumup as $data) {
            $commentId         = $data->SumUpID;
            $data->zan         = $readPartyModel->get_read_plan_money_gift($commentId, $readId);     //取出打赏记录
            $data->commentlist = $readPartyModel->get_read_plan_comment($commentId, $readId); //评论
        }

        $memberMoney   = $readPartyModel->get_member_money($memberInfo->MemNumber, $readId);        //登录者获得的金币
        $totalOutMoeny = $readPartyModel->get_total_out_money($memberInfo->MemNumber, $readId);   //登录者打赏出去的金币

        //企业组织架构 organization
        $organization = [];
        $companyInfo  = [];
        $comDepart    = [];

        if ($readPartyInfo->ReaParType == 1) {
            $companyId = $readPartyInfo->company_id;


            if ($companyId > 0) { //没有公司的，分到未分组里面去
                $companyModel = new CompanyModel();
                $companyInfo  = $companyModel->get_company_info($companyId);
                $departments  = $companyModel->get_company_department($companyId);

                foreach ($departments as $depart) {
                    $partInfo = [
                        'departmentName' => $depart->department_name,
                        //'members'           => $readPartyModel->get_read_party_department_member($readId,$depart->department_id)
                        'members' => [],
                        'departmentId' => $depart->department_id
                    ];
                    array_push($comDepart, $partInfo);
                }
            }

            //$members    = $readPartyModel->get_read_party_department_member($readId,0);
            //$partInfo   = ['departmentName'=>'未分组',"members"=>$members];
            //array_push($comDepart,$partInfo);
        }

        $organization['companyInfo'] = $companyInfo;
        $organization['deparments']  = $comDepart;

        $readPartyInfo->outMoney    = $totalOutMoeny;
        $readPartyInfo->memberMoney = $memberMoney;

        $apiData->message = "ok";
        $apiData->code    = "200";
        $apiData->set_data('bookInfo', $bookInfo)
            ->set_data('readPartyInfo', $readPartyInfo)
            ->set_data('organization', $organization)
            ->set_data('readPlanList', $bookSumup)
            ->set_data('frontMembers', $frontMembers);

        return $apiData->send();


        /*  $apiData->set_data('memberMoney',$memberMoney)
              ->set_data('outMoney',$totalOutMoeny)
              ->set_data('ruledetail',$readPartyInfo->Regulation)
              ->set_data('bookplanlist',$bookSumup)
              ->set_data('readingdetail',$arrayReadingParty)
              ->set_data('memberlist',$readPartyMembers);
          return $apiData->send();*/
    }

    /**
     * 改进计划分页
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function paginate_book_sumup(Request $request)
    {
        $apiData      = new ApiData();
        $mobile       = $request->input('mobile');
        $key          = $request->input('key');
        $parid        = $request->input('parid');
        $bookId       = $request->input('id');
        $page         = $request->input('page');
        $departmentId = $request->input('departmentId', -1);
        $params       = [
            'mobile' => [$mobile, '缺少手机号', '2037'],
            'key' => [$key, "缺少设备ID", '2038'],
            'bookId' => [$bookId, '缺少书籍ID', '6001'],
            'parid' => [$parid, "缺少读书会ID", '6005'],
            'page' => [$page, "缺少页数", '6002']
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }
        $bookModel      = new BookModel();
        $bookSumup      = $bookModel->get_read_plan_by_book_readparty($bookId, $parid, $departmentId);
        $readPartyModel = new ReadPartyModel();
        foreach ($bookSumup as $data) {
            $readPartyId = $parid;
            $commentId   = $data->SumUpID;
            //取出该评论的打赏记录
            $zanList   = $readPartyModel->get_read_plan_money_gift($commentId, $readPartyId);
            $data->zan = $zanList;
            //评论
            $commentreply      = $readPartyModel->get_read_plan_comment($commentId, $readPartyId);
            $data->commentlist = $commentreply;
        }
        $apiData->message = "ok";
        $apiData->code    = "200";
        $apiData->set_data('readPlanList', $bookSumup);
        return $apiData->send_old();
    }





    /*========= 2. 创建个人、企业读书会 =============*/


    /**
     * 创建个人读书会 类型:2
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_personal_read_party(Request $request)
    {
        $request->offsetSet('readPartyType', 2);
        $apiData = $this->add_read_party($request);
        return $apiData->send();
    }


    /**
     * 添加公司读书会 type:1
     * */
    public function add_company_read_party_v3(Request $request)
    {
        $request->offsetSet('readPartyType', 1);
        $apiData = $this->add_read_party($request);
        return $apiData->send();
    }


    /**
     * 创建读书会
     * @param request 环境数据
     * @return ApiDATA
     * */
    public function add_read_party(Request $request)
    {
        define('_qiye_', 1);
        define('_geren_', 2);

        $apiData     = new ApiData();
        $readModel   = new ReadPartyModel();
        $memberModel = new MemberModel();

        $mobile = $request->input('mobile');
        $appKey = $request->input('key');

        $memberInfo = $memberModel->get_member_info_by_mobile_key($mobile, $appKey);
        $userId     = $memberInfo->UserID;
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3005";
            return $apiData;
        }
        $readPartyName = $request->input('reaparname');
        $regulation    = $request->input('regulation');

        //0.检查参数
        $paras  = [
            'readPartyName' => [$readPartyName, '读书会名称不能为空', '10001'],
            'regulation' => [$regulation, '读书会规则不能为空', '1002']
        ];
        $result = $this->check_params($paras);
        if ($result->code != '200') {
            $apiData->code    = $result->code;
            $apiData->message = $result->message;
            return $apiData;
        }

        //1.检查读书会是否被创建
        if ($readModel->check_read_party_name_exists($readPartyName) == true) {
            $apiData->code    = "2001";
            $apiData->message = "读书会名称已被使用";
            return $apiData;
        }
        $readPartyType = $request->input('readPartyType');

        //1：企业读书会 2：个人读书会

        //2.如果创建的是企业读书会
        if ($readPartyType == _qiye_) {
            $companyModel = new CompanyModel();
            //2.1判断公司情况
            $companySn   = trim($request->input('companySn'));
            $companyInfo = $companyModel->get_company_info_by_sn($companySn);

            if ($companyInfo == false) {
                $apiData->message = "公司不存在";
                $apiData->code    = "5002";
                return $apiData;
            }
            $companyId = $companyInfo->company_id;

            //检查本公司是否已经有了读书会
            $companyReadPartys = $companyModel->get_company_read_partys($companyId);
            if (count($companyReadPartys) > 0) {
                $apiData->code    = "5003";
                $apiData->message = "该公司编号已被使用";
                return $apiData;
            }

            //2.2判断当前用户是否是管理员
            /* if($memberInfo->UserID != $companyInfo->manager_user_id){
                $apiData->code      = "5002";
                $apiData->message   = "您不是公司管理员，无法创建读书会";
                return $apiData;
            }*/
        } else {
            $companyId = 0;
        }

        $companyname   = $request->input('companyname');
        $tel           = $request->input('tel');
        $createrName   = $request->input('creatername');
        $readPartyData = [
            'States' => 1,
            'Tel' => $tel,
            'ReaParType' => $readPartyType,
            'Regulation' => $regulation,
            'ReaParName' => $readPartyName,
            'MemNumber' => $memberInfo->MemNumber,
            'company_id' => $companyId,
            'companyname' => $companyname,
            'CreaterName' => $createrName,
        ];

        $readPartyId = $readModel->add_read_party($readPartyData);

        //将创建者拉入读书会  如果是应该有一个部门
        $result = $readModel->add_read_party_member($readPartyId, $userId);
        if ($readPartyType == _qiye_) {
            $data       = [
                'UserID' => $memberInfo->UserID,
                'States' => 1,
            ];
            $memberModel->update_member_info($data);


            //检查用户是否已存在该公司 如果不是 加入该公司 扣除端口
            if ($companyModel->company_exists_member($companyId, $userId) == false) {
                $companyModel->add_company_member($companyId, 0, $userId);
                $companyModel->use_company_port($companyId, 1);
            }

            $memberModel->change_member_endtime($userId);
            
        }


        if ($result != true) {
            $apiData->code    = "403";
            $apiData->message = "读书会添加失败";
        }


        //3.保存图片
        $imgName      = $request->input('imgName');
        $readPartyImg = $request->file('readPartyImg');
        $msg          = "";
        if ($imgName) {
            $filetype = explode('.', $imgName);
            if (!isset($filetype[1]) || !in_array($filetype[1], $this->fileTypes)) {
                $msg = "图片类型未知或图片格式不在允许范围内";
            } else {
                //文件上传路径
                $facepath = 'groupface';
                $fileName = "1-" . $readPartyId . '.' . $filetype[1];

                $file = Storage::putFileAs($facepath, $readPartyImg, $fileName);
                if ($file == '') {
                    $msg = "图片保存失败";
                } else {

                    $data = ['FilePath1' => "/uploads/" . $file];
                    $readModel->update_read_party($readPartyId, $data);
                }
            }
        }

        $apiData->set_data('readPartyId', $readPartyId);
        $apiData->code    = '200';
        $apiData->message = '读书会添加成功,' . $msg;
        return $apiData;
    }



    /*========== 3.管理读书会 =================*/
    /**
     * 删除读书会
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function readingPartyDelete(Request $request)
    {
        $result    = 'no';
        $rules     = [
            'id' => 'required',
            'mobile' => 'required',
            'key' => 'required',
            'timestamp' => 'required',
            'sign' => 'required'
        ];
        $messages  = [
            'id.required' => '2039',
            'mobile.required' => '2037',
            'key.required' => '2038',
            'timestamp.required' => '2040',
            'sign.required' => '2041'
        ];
        $id        = $request->input('id');
        $mobile    = $request->input('mobile');
        $key       = $request->input('key');
        $sign      = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params    = ['mobile' => $mobile, 'key' => $key, 'id' => $id, 'timestamp' => $timestamp, 'sign' => $sign];
        $v         = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        if ($this->checkSign($params) == true) {
            $member = $this->memNumber($mobile, $key);
            if (count($member) > 0) {
                $entReadingParty = EntReadingParty::find($id);
                if ($member->MemNumber == $entReadingParty->MemNumber) {
                    EntReadingParty::where('ReaParID', $entReadingParty->ReaParID)->update(['DeleteMark' => '0']);
                    return response()->json(['message' => 'ok', 'code' => '200']);
                } else {
                    //权限不足
                    return response()->json(['message' => $result, 'code' => '3069']);
                }
            } else {
                return response()->json(['message' => $result, 'code' => '3027']);
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3028']);
        }
    }


    /**
     * 修改读书会头像 1--小图 2--大图
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update_read_party_img(Request $request)
    {
        $id     = $request->input('id');
        $type   = $request->input('type');
        $name   = $request->input('name');
        $mobile = $request->input('mobile');
        $key    = $request->input('key');


        $params = [
            'id' => [$id, '缺少读书会ID', '2098'],
            'mobile' => [$mobile, '缺少手机号', '2073'],
            'key' => [$key, '缺少key', '2070'],
            'name' => [$name, '缺少图片名称', '2069'],
            'type' => [$type, '不知道是小图还是大图', '2099'],
        ];

        $apiData = new ApiData();

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3052";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($id);
        if ($readPartyInfo == false) { //读书会信息读取失败
            $apiData->message = "读书会不存在";
            $apiData->code    = "3076";
            return $apiData->send();
        }


        if ($memberInfo->MemNumber != $readPartyInfo->MemNumber) { //没有修改头像的权限
            $apiData->message = "权限不足";
            $apiData->code    = "3077";
            return $apiData->send();
        }


        $filetype = explode('.', $name);
        if (!isset($filetype[1]) || !in_array($filetype[1], $this->fileTypes)) {
            $apiData->message = "图片类型未知或图片格式不在允许范围内";
            $apiData->code    = "3053";
            return $apiData->send();
        }


        //文件上传路径
        $facepath = 'groupface';
        $fileName = $type . "-" . $id . '-' . time() . '.' . $filetype[1];
        $file     = Storage::putFileAs($facepath, $request->file('img'), $fileName);
        if ($file == '') {
            $apiData->message = "图片保存失败";
            $apiData->code    = "3055";
            return $apiData->send();
        }

        $memfacceurl = '/uploads/' . $file;
        $fileColum   = "FilePath" . $type;
        $readData    = [$fileColum => $memfacceurl];
        $readPartyModel->update_read_party($id, $readData);

        $apiData->message = "保存成功";
        $apiData->code    = "200";
        $apiData->set_data('file', env('ADMIN_HOST') . $memfacceurl);
        return $apiData->send_old();
    }


    /**
     * 管理员修改群规
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update_read_party_gulation(Request $request)
    {
        $request->offsetSet('readPartyId', $request->input('id'));
        return $this->update_read_party_info($request);
    }


    /*
     * 修改读书会信息
     * */
    public function update_read_party_info(Request $request)
    {
        $apiData = new ApiData();


        $readPartyId = $request->input('readPartyId');
        $mobile      = $request->input('mobile');
        $key         = $request->input('key');

        $params = [
            'mobile' => [$mobile, "手机号为空", "2082"],
            'key' => [$key, "设备ID为空", "2083"],
            'id' => [$readPartyId, "读书会ID为空", "2093"],
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3056";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);
        if ($readPartyInfo == false) {
            $apiData->message = "读书会不存在";
            $apiData->code    = "3069";
            return $apiData->send();
        }

        if ($memberInfo->MemNumber != $readPartyInfo->MemNumber) {
            $apiData->message = "权限不足";
            $apiData->code    = "3069";
            return $apiData->send();
        }


        //修改名称

        $newReadPartyInfo = [
            'Regulation' => $request->input('regulation'),
            'CompanyName' => $request->input('companyName'),
            'Tel' => $request->input('tel'),
            'ReaParName' => $request->input('readPartyName'),
            'createrName' => $request->input('createrName'),
        ];
        $newReadPartyInfo = array_filter($newReadPartyInfo);

        $result = $readPartyModel->update_read_party($readPartyId, $newReadPartyInfo);
        if ($result) {
            $apiData->message = "读书会信息修改成功";
            $apiData->code    = "200";
        } else {
            $apiData->message = "读书会修改失败";
            $apiData->code    = "3059";
        }
        return $apiData->send();

    }

    /*========== 4.读书会会员管理 ===========


    =====*/

    /**
     * 会员通讯录中哪些用户可以添加为会员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function check_member_mobile_list(Request $request)
    {
        $beginTime = time();

        $data = '[{"name":"张维喜","mobileList":["150006069424","x13540381839"]},{"name":"王五","mobileList":["18604074775","xxx","xxx"]}]';

        $readPartyId = $request->input('id');        //读书会ID
        $mobile      = $request->input('mobile');
        $key         = $request->input('key');
        $moblist     = $request->input('userList');
        $userList    = json_decode(urldecode($moblist));


        $params = [
            'mobile' => [$mobile, "手机号为空", "2037"],
            'key' => [$key, "设备ID异常", "2038"],
            'id' => [$readPartyId, "读书会ID异常", "2039"],
            'moblist' => [$userList, "会员列表异常", "6002"]
        ];

        $apiData = new ApiData();
        $apiData->set_data('memberlist', []);

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->code    = $checkResult->code;
            $apiData->message = $checkResult->message;

            return $apiData->send();
        }


        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);


        if ($memberInfo == false) {
            $apiData->message = "用户验证失败";
            $apiData->code    = "3027";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);

        //1.检查权限
        if ($readPartyInfo->MemNumber != $memberInfo->MemNumber) {
            $apiData->message = "只有管理员才能添加会员";
            $apiData->code    = "3078";
            return $apiData->send();
        }

        //遍历用户
        $users = [];
        foreach ($userList as $key => $user) {

            $userInfo = [
                'isVip' => 0,   //是否是会员  0:不是 1:是
                'needInvite' => 0,   //是否需要邀请 0:不邀请 1：邀请
                'headImg' => "",
                'memNumber' => "",
                'yourName' => $user->name
            ];

            $inviterMobiles = $user->mobileList;    //一个用户可能有多个手机号码 所以对手机号码进行逐个判断
            foreach ($inviterMobiles as $inviterMobile) {
                //获取被邀请者信息
                $inviterInfo = $memberModel->get_member_info_by_mobile($inviterMobile);
                if ($inviterInfo == false || $inviterInfo->States != '1') {
                    continue;
                }

                $userInfo['isVip']     = 1;    //用户存在
                $userInfo['memNumber'] = $inviterInfo->MemNumber;
                $userInfo['headImg']   = $inviterInfo->headImg;

                //检查用户是否加入了读书会
                $isJoinRead = $readPartyModel->check_read_party_member_exists($readPartyId, $inviterInfo->UserID);
                if ($isJoinRead == true) {

                    break;
                } else {
                    $userInfo['needInvite'] = 1; //用户未加入读书会，可以邀请
                }
            }
            if ($userInfo['isVip'] == 1) {
                array_push($users, $userInfo);
            }
        }
        $endTime = time();

        $apiData->message = "ok";
        $apiData->code    = "200";
        $apiData->set_data('memberlist', $users);
        return $apiData->send_old();
    }


    /**
     * 添加读书会成员   从通讯录中添加
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_read_party_member(Request $request)
    {
        define('_qiye_', 1);
        define('_geren_', 2);

        $apiData = new ApiData();

        $readId = $request->input('id');
        $mobile = $request->input('mobile');
        $key    = $request->input('key');
        $memid  = $request->input('memid');

        $userMobile   = $request->input('userMobile');
        $userName     = $request->input('userName');
        $job          = $request->input('job');
        $rewardRight  = $request->input('rewardRight') == 1 ? true : false;
        $departmentId = $request->input('departmentId');

        $data = [
            'id' => [$readId, "缺少读书会ID", '2039'],
            'mobile' => [$mobile, "缺少手机号", '2037'],
            'key' => [$key, "缺少设备ID", "2038"]
        ];

        $result = $this->check_params($data);
        if ($result->code != '200') {
            $apiData->message = $result->message;
            $apiData->code    = $result->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();

        //1.检查登录者
        $managerInfo = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($managerInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();

        //2.检查读书会
        $readPartyInfo = $readPartyModel->get_read_party_info($readId);
        if (count($readPartyInfo) == 0) { //读书会信息读取失败
            $apiData->message = "读书会不存在";
            $apiData->code    = "3065";
            return $apiData->send();
        }


        //3.检查是否是管理员
        if ($managerInfo->MemNumber != $readPartyInfo->MemNumber) { //权限不足
            $apiData->message = "权限不足";
            $apiData->code    = "3066";
            return $apiData->send();
        }

        //4.检查该读书会是个人读书会还是企业读书会  企业读书会是需要限制端口数量的  1:企业 2.个人
        if ($readPartyInfo->ReaParType == _qiye_) {

            if (!preg_match('/^1\d{10}$/', $userMobile)) {
                return $apiData->send("3021", "手机号格式错误");
            }


            //获取企业信息
            $companyModel = new CompanyModel();
            $companyInfo  = $companyModel->get_company_info($readPartyInfo->company_id);
            $companyId    = $companyInfo->company_id;
            $beginTime    = strtotime($companyInfo->vip_begin_date);
            $endTime      = strtotime($companyInfo->vip_end_date);
            $time         = time();


            //4.2检查企业的有效期
            if ($beginTime > $time || $endTime < $time) {
                $apiData->code    = "3066";
                $apiData->message = "企业的有效服务期已失效";
                return $apiData->send();
            }
        }

        //6.检查被添加的会员是否存在

        if ($readPartyInfo->ReaParType == _geren_) {

            //6.1判断被添加用户是否存在
            $invitedMember = $memberModel->get_member_info_by_member_number($memid);
            if ($invitedMember == false) {
                $apiData->message = "被邀请的会员不存在";
                $apiData->code    = "3067";
                return $apiData->send();
            }
        } elseif ($readPartyInfo->ReaParType == _qiye_) {
            $invitedMember = $memberModel->get_member_info_by_mobile($userMobile);
        }


        //检查该用户是否加入了读书会
        if ($invitedMember) {
            $isExists = $readPartyModel->check_read_party_member_exists($readId, $invitedMember->UserID);
            if ($isExists == true) {
                $apiData->message = "该用户已是读书会会员";
                $apiData->code    = "3102";
                return $apiData->send();
            }
        }


        if ($readPartyInfo->ReaParType == _qiye_) {
            //如果系统不存在员工或则员工不存在公司里边
            $needCheck = false;
            if ($invitedMember == false) {
                $needCheck = true;
            } elseif (!$companyModel->company_exists_member($companyId, $invitedMember->UserID)) {
                $needCheck = true;
            }

            //4.3检查企业的端口数量
            if ($needCheck && $companyInfo->surplus_port <= 0) {
                return $apiData->send("3066", "端口不足");
            }

            //新添加的会员的时间 = 个人时间 + 公司时间
            if ($invitedMember == false) {
                $userInfo = [
                    "MemNumber" => create_member_number(),
                    "UserName" => $userMobile,
                    "NickName" => $userName,
                    "YourName" => $userName,
                    "RegisterType" => "企业加入",
                    'AppKey' => "",
                    "wx_unionid" => "",
                    'app_openid' => "",
                    'head_img' => "",
                    'sex' => "n",
                ];
                $memberModel->register($userInfo);
                $invitedMember = $memberModel->get_member_info_by_mobile($userMobile);
            }

            //检查用户是否加入该公司 设置会员的部门ID 修改会员的有效时间

            $userId = $invitedMember->UserID;

            if ($companyModel->company_exists_member($companyId, $userId)) {
                //已存在 则修改
                $companyModel->update_company_member($userId, $companyId, ['department_id' => $departmentId, 'job' => $job]);
            } else {
                //不存在  则添加 并扣除端口
                $companyModel->add_company_member($companyId, $departmentId, $userId, $job);
                $companyModel->use_company_port($companyId, 1);
            }
            $updateInfo  = [
                "States" => 1,               //会员状态
                'UserID' => $userId
            ];
            $memberModel->update_member_info($updateInfo);
            $memberModel->change_member_endtime($userId);
        }

        try {
            $readPartyModel->add_read_party_member($readId, $invitedMember->UserID, $rewardRight);
            //发送消息推送
            $msg      = $readPartyInfo->ReaParName . "读书会会长" . $managerInfo->YourName . "邀请您加入读书会";
            $msgModel = new MessageModel();
            $msgId    = $msgModel->add_note_message('读书会邀请', $msg);
            $msgModel->add_user_message($msgId, $invitedMember->UserID);

            $jpush        = new Jpush();
            $jpush->alias = $invitedMember->UserName;
            $jpush->set_message($msg);
            $resutl = $jpush->send();
        } catch (Exception $e) {
            return $apiData->send("3067", "加入失败");
        }
        return $apiData->send('200', 'ok');
    }


    /**
     * 读书俱乐部的所有成员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function read_party_all_member(Request $request)
    {
        $apiData     = new ApiData();
        $readPartyId = $request->input('id');
        $page        = $request->input('page');
        $keyword     = $request->input('keyword');
        $mobile      = $request->input('mobile');
        $key         = $request->input('key');
        $depatmentId = $request->input('departmentId', -1);
        $depatmentId = $depatmentId === '' ? -1 : $depatmentId;

        $params = [
            'mobile' => [$mobile, "缺少手机号", "2037"],
            'key' => [$key, "缺少设备ID", "2038"],
            'id' => [$readPartyId, "缺少读书会ID", "2039"]
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }


        //读书会信息
        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);
        if (!$readPartyInfo) {
            $apiData->message = "读书会不存在";
            $apiData->code    = "402";
            return $apiData->send();
        }

        $groupid   = $readPartyInfo->ReaParID;
        $groupname = $readPartyInfo->ReaParName;
        $addDate   = $readPartyInfo->AddDate;
        $rule      = $readPartyInfo->Regulation;

        if ($depatmentId >= 0) {
            $readPartyMembers = $readPartyModel->get_read_party_department_member($readPartyId, $depatmentId);
        } else {

            $readPartyMembers = $readPartyModel->get_read_party_member($readPartyId, $keyword, 1000);
        }


        //是否是群主 0--不是 1--是
        $isadmin = 0;
        if ($readPartyInfo->MemNumber == $memberInfo->MemNumber) {
            $isadmin = 1;
        }

        foreach ($readPartyMembers as $v) {
            if ($v->MemNumber == $readPartyInfo->MemNumber) {
                $v->isAdmin = 1;
            } else {
                $v->isAdmin = 0;
            }
            $v->StudyMoney = $v->StudyMoney ? $v->StudyMoney : 0;
        }

        $apiData->message = "ok";
        $apiData->code    = "200";
        $apiData->set_data('groupid', $groupid)
            ->set_data('groupname', $groupname)
            ->set_data('rule', $rule)
            ->set_data('time', $addDate)
            ->set_data('isadmin', $isadmin)
            ->set_data('memberlist', $readPartyMembers);
        return $apiData->send_old();
    }

    /**
     * 读书会部门成员
     * */
    public function read_party_department_member(Request $request)
    {
        $mobile       = $request->input('mobile');
        $key          = $request->input('key');
        $readPartyId  = $request->input('readPartyId');
        $departmentId = $request->input('departmentId');
        $apiData      = new ApiData();

        $readPartyModel   = new ReadPartyModel();
        $members          = $readPartyModel->get_read_party_department_member($readPartyId, $departmentId);
        $apiData->message = "获取成功";
        $apiData->code    = "200";
        $apiData->set_data('members', $members);
        return $apiData->send();
    }


    /**
     * 读书会会员详细信息
     *
     * */
    public function read_party_member_detail(Request $request)
    {
        $readPartyId = $request->input('readPartyId');
        $userId      = $request->input('userId');
        $apiData     = new ApiData();
        $memberModel = new MemberModel();
        $userInfo    = $memberModel->get_member_info_by_id($userId);
        if (!$userInfo) {
            $apiData->message = "用户不存在";
            $apiData->code    = "2002";
            return $apiData->send();
        }
        unset($userInfo->LoginKey);
        unset($userInfo->AppKey);


        $readPartyModel        = new ReadPartyModel();
        $bookModel             = new BookModel();
        $readPartyMemberDetail = $readPartyModel->get_read_party_member_detail($userInfo->UserID, $readPartyId);
        if ($readPartyMemberDetail == false) {
            $apiData->message = "用户已被移出读书会";
            $apiData->code    = "2002";
            return $apiData->send();
        }
        $companyModel      = new CompanyModel();
        $readPartyInfo     = $readPartyModel->get_read_party_info($readPartyId);
        $companyId         = $readPartyInfo->company_id;
        $memberCompanyInfo = $companyModel->get_company_member_info($companyId, $userId);

        $departmentId = $memberCompanyInfo->department_id;

        if ($departmentId > 0) {
            $userInfo->department_name = $memberCompanyInfo->department_name;
            $userInfo->department_id   = $departmentId;
        } else {
            $userInfo->department_name = "未分组";
            $userInfo->department_id   = 0;
        }
        $userInfo->job              = $memberCompanyInfo->job;
        $readedBook                 = $bookModel->get_user_readed_book($userInfo->MemNumber);
        $userInfo->isEmployee       = $readPartyMemberDetail->is_delete === 1 ? 0 : 1;
        $userInfo->rewardRight      = $readPartyMemberDetail->reward_right;
        $userInfo->readedBookNumber = count($readedBook);
        $apiData->message           = "ok";
        $apiData->code              = "200";
        $apiData->set_data('memberInfo', $userInfo);

        return $apiData->send();
    }

    /**
     * 退出读书会
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function quit_read_party(Request $request)
    {
        $apiData     = new ApiData();
        $readPartyId = $request->input('id');
        $mobile      = $request->input('mobile');
        $key         = $request->input('key');

        $params      = [
            'mobile' => [$mobile, "缺少手机号", "2037"],
            'key' => [$key, "缺少设备ID", "2038"],
            'readPartyid' => [$readPartyId, "缺少读书会ID", "2039"]
        ];
        $paramsCheck = $this->check_params($params);
        if ($paramsCheck->status == false) {
            $apiData->message = $paramsCheck->message;
            $apiData->code    = $paramsCheck->code;
            return $apiData->send();
        }
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();
        $result         = $readPartyModel->remove_party_member($readPartyId, $memberInfo->UserID);
        if ($result) {
            $apiData->message = "退出读书会成功";
            $apiData->code    = "200";
        } else {
            $apiData->message = "退出读书会失败";
            $apiData->code    = "3027";
        }
        return $apiData->send();
    }


    /**
     * 管理员删除读书会成员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function manager_remove_read_party_member(Request $request)
    {
        mylogger('zhangweixi');
        mylogger($request->all());
        $apiData     = new ApiData();
        $readPartyId = $request->input('id');
        $memid       = $request->input('memid');
        $mobile      = $request->input('mobile');
        $key         = $request->input('key');
        $sign        = $request->input('sign');
        $timestamp   = $request->input('timestamp');

        $params = [
            'mobile' => [$mobile, "缺少手机号", "2037"],
            'key' => [$key, "缺少设备ID", "0238"],
            'id' => [$readPartyId, "缺少读书会ID", "2039"],
            'memid' => [$memid, "缺少会员ID", '2110'],
            //'timestamp' => [$timestamp,"缺少时间戳","2040"],
            //'sign'      => [$sign,"缺少签名","2041"]
        ];

        $paCheckResult = $this->check_params($params);
        if ($paCheckResult->status == false) {
            $apiData->message = $paCheckResult->message;
            $apiData->code    = $paCheckResult->code;
            return $apiData->send();
        }
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);
        if ($readPartyInfo->MemNumber != $memberInfo->MemNumber) {
            $apiData->message = "权限不足";
            $apiData->code    = "3013";
            return $apiData->send();
        }

        $readPartyMemberInfo = $memberModel->get_member_info_by_member_number($memid);
        $userId              = $readPartyMemberInfo->UserID;
        $result              = $readPartyModel->remove_party_member($readPartyId, $userId);
        if ($result) {
            $apiData->message = "删除成功";
            $apiData->code    = "200";
            //EntReaParLog::where('MemNumber', $memid)->where('ReaParID', $id)->delete();
        } else {
            $apiData->message = "删除失败";
            $apiData->code    = "3027";
        }
        return $apiData->send();
    }


    /**
     * 修改读书会会员信息
     * */
    public function update_read_party_member(Request $request)
    {

        $mobile       = $request->input('mobile');
        $key          = $request->input('key');
        $departmentId = $request->input('departmentId');
        $readPartyId  = $request->input('readPartyId');
        $job          = $request->input('job');
        $isEmployee   = $request->input('isEmployee', 0);
        $rewardRight  = $request->input('rewardRight');
        $userId       = $request->input('userId');
        $userMobile   = $request->input('userMobile');
        $apiData      = new ApiData();

        $params = [
            'departmentId' => [$departmentId, '缺少部门ID', '2003'],
            'job' => [$job, '缺少工作名称', '2004'],
            'userMobile' => [$userMobile, '修改的手机号为空', '2006'],
            'userId' => [$userId, '用户的ID为空', '2007']
        ];


        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "2001";
            return $apiData->send();
        }


        $updatedUserInfo = $memberModel->get_member_info_by_id($userId);
        if ($updatedUserInfo == false) {
            $apiData->message = "被修改的用户不存在";
            $apiData->code    = "2002";
            return $apiData->send();
        }

        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);
        $companyId      = $readPartyInfo->company_id;

        $companyModel = new CompanyModel();

        //判断状态 修改企业端口 和 员工有效时间
        if ($isEmployee == 0) { //离职处理

            //1.从读书会移除
            $readPartyModel->remove_party_member($readPartyId, $userId);

            //检查是否还存在本公司的其他读书会 如果不存在 则移出本公司
            $count = DB::table('read_party_member as a')
                ->leftJoin('read_party as b', 'b.ReaParID', '=', 'a.read_party_id')
                ->where('b.company_id', $companyId)
                ->where('a.read_party_id', '<>', $readPartyId)
                ->count();

            if ($count == 0) {  //不存在其他读书会 从公司删除 删除后自动恢复端口
                $companyModel->delete_company_member($companyId, $userId);
                $memberModel->change_member_endtime($userId);
            }
            $apiData->send('200', '删除成功');
        }

        //修改用户公司信息
        $companyMemberInfo = ['job' => $job, 'department_id' => $departmentId];
        $companyModel->update_company_member($userId, $companyId, $companyMemberInfo);


        //修改用户基本信息
        $modifyInfo = [
            'UserID' => $updatedUserInfo->UserID,
            'UserName' => $userMobile
        ];
        $memberModel->update_member_info($modifyInfo);


        //修改读书会相关信息
        $partyMemberInfo = ['reward_right' => $rewardRight];
        $readPartyModel->update_read_party_member($readPartyId, $userId, $partyMemberInfo);
        return $apiData->send("200", "修改成功");
    }






    /*========= 5.读书会的读书信息 =============*/
    /* 读书改进计划：是指会员在观看视频的时候，同时在输入栏里写入的当时的一些所得和感受
     * 评论：是指其他会员给读书改进计划下做的评论
     * 打赏：是指其他成员读书改进计划者的金币打赏
     * */

    /**
     * 获得单条读书计划信息
     *
     */
    public function get_read_plan_info(Request $request)
    {

        $apiData     = new ApiData();
        $readPlanId  = $request->input('commentId');
        $readPartyId = $request->input('readPartyId');
        $mobile      = $request->input('mobile');
        $appKey      = $request->input('key');

        $params = [
            "mobile" => [$mobile, "手机号为空"],
            "key" => [$appKey, "APP设备ID为空"],
            "readPartyId" => [$readPartyId, "读书会ID为空"],
            "readPlanId" => [$readPlanId, "读书改进计划ID为空"]
        ];


        $paramsCheck = $this->check_params($params);
        if ($paramsCheck->status == false) {
            $apiData->message = $paramsCheck->message;
            $apiData->code    = "400";
            return $apiData->send();
        }

        $userModel = new MemberModel();
        $userInfo  = $userModel->get_member_info_by_mobile_key($mobile, $appKey);
        if ($userInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "401";
            return $apiData->send();
        }


        $bookModel    = new BookModel();
        $readPlanInfo = $bookModel->get_comment_info($readPlanId);

        unset($readPlanInfo->UserID);
        unset($readPlanInfo->UserName);
        unset($readPlanInfo->NickName);

        $readModel                 = new ReadPartyModel();
        $zanList                   = $readModel->get_read_plan_money_gift($readPlanId, $readPartyId); //取出该评论的打赏记录
        $readPlanInfo->zan         = $zanList;
        $comments                  = $readModel->get_read_plan_comment($readPlanId, $readPartyId); //评论
        $readPlanInfo->commentlist = $comments;
        $apiData->message          = "ok";
        $apiData->code             = "200";
        $apiData->set_data('data', $readPlanInfo);
        return $apiData->send_old();
    }


    /**
     * （一本书在某个俱乐部会员下的）全部评论
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sumupComment(Request $request)
    {
        $result = 'no';
        $rules  = [
            'id' => 'required',
            'type' => 'required',
            'parid' => 'required',
            'mobile' => 'required',
            'key' => 'required'
        ];

        $messages = [
            'id.required' => '2039',
            'type.required' => '2094',
            'parid.required' => '2093',
            'mobile.required' => '2037',
            'key.required' => '2038'
        ];
        $id       = $request->input('id');
        $type     = $request->input('type');
        $parid    = $request->input('parid');
        $mobile   = $request->input('mobile');
        $key      = $request->input('key');


        $params = [
            'mobile' => $mobile,
            'key' => $key,
            'id' => $id,
            'type' => $type,
            'parid' => $parid
        ];


        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        $member = $this->memNumber($mobile, $key);
        if (count($member) > 0) {
            $entBookSumUp = DB::table('vw_app_booksumup')
                ->select('SumUpID', 'UserName', 'FilePath1', 'YourName', 'BookReview1', 'BookReview2', 'BookReview3', 'BookReview4', 'commsum1', 'commsum2', 'commsum3', 'commsum4', 'AddDate')
                ->where('SumUpID', $id)
                ->first();

            if (count($entBookSumUp) > 0) {

                $content = '';
                $commsum = '0';
                switch ($type) {
                    case 1:
                        $content = $entBookSumUp->BookReview1;
                        $commsum = $entBookSumUp->commsum1;
                        break;
                    case 2:
                        $content = $entBookSumUp->BookReview2;
                        $commsum = $entBookSumUp->commsum2;
                        break;
                    case 3:
                        $content = $entBookSumUp->BookReview3;
                        $commsum = $entBookSumUp->commsum3;
                        break;
                    case 4:
                        $content = $entBookSumUp->BookReview4;
                        $commsum = $entBookSumUp->commsum4;
                        break;
                }
                //是否点赞过
                $checkZan = EntCommZanLog::select('ZanID')->where('MemNumber', $member->MemNumber)->where('Type', $type)->where('CommID', $id)->first();
                $zancolor = 0;
                if (count($checkZan) > 0) {
                    $zancolor = 1;
                }
                //改进计划详细
                $sunupdetail = ['id' => $entBookSumUp->SumUpID, 'name' => $entBookSumUp->YourName, 'url' => $entBookSumUp->FilePath1, 'content' => $content, 'commsum' => $commsum, 'zancolor' => $zancolor, 'time' => $entBookSumUp->AddDate];
                //评论列表
                $entCommentReply = DB::table('vw_app_commentreply')->select('RepID', 'AddDate', 'CommContents', 'YourName', 'FilePath1', 'commsum')->where('States', '1')->where('DeleteMark', '1')->where('ReaParID', $parid)->where('CommID', $id)->where('Type', $type)->orderBy('AddDate', 'desc')->simplePaginate(6);
                return response()->json(['message' => 'ok', 'code' => '200', 'sunupdetail' => $sunupdetail, 'replylist' => $entCommentReply]);
            } else {
                //改进计划不存在
                return response()->json(['message' => $result, 'code' => '3073']);
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3027']);
        }
    }


    /**
     * 添加对读书改进计划的评论
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_read_plan_comment(Request $request)
    {
        $result = 'no';
        $rules  = [
            'id' => 'required',
            'type' => 'required',
            'parid' => 'required',
            'content' => 'required',
            'mobile' => 'required',
            'key' => 'required',
        ];

        $messages = [
            'id.required' => '2039',
            'type.required' => '2094',
            'parid.required' => '2093',
            'content.required' => '2095',
            'mobile.required' => '2037',
            'key.required' => '2038',
        ];

        $id      = $request->input('id');//父级ID  |booksumup用户读书改进计划的主键ID
        $mobile  = $request->input('mobile');//手机号
        $type    = $request->input('type');//默认为0就可以
        $parid   = $request->input('parid');//读书会ID
        $content = $request->input('content');//评论的内容
        $key     = $request->input('key');//设备的ID
        $params  = [
            'mobile' => $mobile,
            'key' => $key,
            'id' => $id,
            'type' => $type,
            'parid' => $parid,
            'content' => $content,
        ];
        $v       = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        $memberModel = new MemberModel(); //会员信息的Model
        $member      = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($member == false) {
            return response()->json(['message' => $result, 'code' => '3027']);//如果用户手机没有会员信息则没有登录
        }

        $entCommentReply               = new EntCommentReply();//回复读书改进计划的评论
        $entCommentReply->States       = 1;
        $entCommentReply->Type         = $type;
        $entCommentReply->CommContents = emoji_text_encode($content);
        $entCommentReply->CommID       = $id;//读书改进计划的内容的ID
        $entCommentReply->ReaParID     = $parid;//读书会的ID【对应的是read_party】
        $entCommentReply->MemNumber    = $member->MemNumber;
        $entCommentReply->DeleteMark   = 1;//是否已经删除1为没有删除0为已经删除了
        $entCommentReply->ReleaseDate  = date('Y-m-d H:i:s', time());//添加的时间
        $entCommentReply->AddDate      = date('Y-m-d H:i:s', time());//添加的时间
        $entCommentReply->save();

        if ($entCommentReply) {

            $bookModel    = new BookModel();//获取书籍的信息
            $readPlanOwer = $bookModel->get_comment_info($id);//获取摸一个读书改进计划的ID

            //添加消息
            $messageCtrl = new MessageModel();
            $msg         = '读书改进评论:您的好友' . $member->YourName . "评论了你的《" . $readPlanOwer->BookTitle . "》读书改进计划日志";
            $msgId       = $messageCtrl->add_note_message("读书改进评论", $msg);
            $messageCtrl->add_user_message($msgId, $readPlanOwer->UserID);


            //发送消息
            $push        = new Jpush();
            $push->alias = $readPlanOwer->UserName;
            $push->set_message($msg);
            $push->send();
            return response()->json(['message' => 'ok', 'code' => '200']);
        } else {
            //评论失败
            return response()->json(['message' => $result, 'code' => '3074']);
        }

    }



    //=======================以下两个方法不知是否使用了===============================

    /**
     * 评论的回复
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sumupReply(Request $request)
    {
        $result   = 'no';
        $rules    = [
            'id' => 'required',
            'mobile' => 'required',
            'key' => 'required'
        ];
        $messages = [
            'id.required' => '2096',
            'mobile.required' => '2037',
            'key.required' => '2038'
        ];
        $id       = $request->input('id');
        $mobile   = $request->input('mobile');
        $key      = $request->input('key');
        $params   = ['id' => $id, 'mobile' => $mobile, 'key' => $key];
        $v        = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        $member = $this->memNumber($mobile, $key);
        if (count($member) > 0) {
            $entSumupReply = DB::table('vw_app_sumupreply')
                ->select('SuReID', 'ReplyContents', 'AddDate', 'YourName', 'FilePath1')
                ->where('RepID', $id)
                ->get();
            return response()->json(['message' => 'ok', 'code' => '200', 'sumupreplylist' => $entSumupReply]);
        } else {
            return response()->json(['message' => $result, 'code' => '3027']);
        }
    }


    /**
     * 添加回复
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_read_plan_comment_replay(Request $request)
    {
        $result    = 'no';
        $rules     = [
            'id' => 'required',
            'content' => 'required',
            'mobile' => 'required',
            'key' => 'required',
            'timestamp' => 'required',
            'sign' => 'required'
        ];
        $messages  = [
            'id.required' => '2097',
            'content.required' => '2095',
            'mobile.required' => '2037',
            'key.required' => '2038',
            'timestamp.required' => '2040',
            'sign.required' => '2041'
        ];
        $id        = $request->input('id');
        $content   = $request->input('content');
        $mobile    = $request->input('mobile');
        $key       = $request->input('key');
        $sign      = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params    = ['mobile' => $mobile, 'key' => $key, 'id' => $id, 'content' => $content, 'timestamp' => $timestamp, 'sign' => $sign];
        $v         = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        if ($this->checkSign($params) == true) {
            $member = $this->memNumber($mobile, $key);
            if (count($member) > 0) {
                $entSumupReply                = new EntSumupReply();
                $entSumupReply->RepID         = $id;
                $entSumupReply->ReplyContents = $content;
                $entSumupReply->MemNumber     = $member->MemNumber;
                $entSumupReply->AddDate       = date('Y-m-d H:i:s', time());
                $entSumupReply->save();
                if ($entSumupReply) {
                    return response()->json(['message' => 'ok', 'code' => '200']);
                } else {
                    //添加失败
                    return response()->json(['message' => $result, 'code' => '3075']);
                }
            } else {
                return response()->json(['message' => $result, 'code' => '3027']);
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3028']);
        }
    }

    //======================================================


    /**
     * 获取某本书在某读书会下的所有会员的读书改进计划
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function read_party_book_gift(Request $request)
    {
        $apiData      = new ApiData();
        $mobile       = $request->input('mobile');
        $key          = $request->input('key');
        $parid        = $request->input('parid');
        $page         = $request->input('page');
        $bookId       = $request->input('bookId');
        $departmentId = $request->input('departmentId');

        $params = [
            'mobile' => [$mobile, "缺少手机号", "2037"],
            'key' => [$key, "缺少APP设备ID", "2038"],
            'parid' => [$parid, "缺少读书会ID", "6005"],
            'bookId' => [$bookId, "缺少书籍ID", "2039"]
        ];

        $paramsCheck = $this->check_params($params);
        if ($paramsCheck->status == false) {
            $apiData->message = $paramsCheck->message;
            $apiData->code    = $paramsCheck->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3027";
            return $apiData->send();
        }


        $bookModel        = new BookModel();
        $planGift         = $bookModel->get_read_plan_by_book_readparty($bookId, $parid, $departmentId);
        $apiData->message = "ok";
        $apiData->code    = "200";
        $apiData->set_data('pagelist', $planGift);
        return $apiData->send_old();

    }


    /**
     * 会员信息
     * @param string $mobile
     * @param string $key
     * @return mixed
     */
    protected function memNumber($mobile = '', $key = '')
    {
        $memberModel   = new EntMemberInfo();
        $entMemberInfo = $memberModel->get_member_info_by_mobile_and_appkey($mobile, $key);
        return $entMemberInfo;
    }


    protected function memNumberTwo($memid = '')
    {

        $entMemberInfo = EntMemberInfo::select('States', 'MemEndTime', 'FilePath1', 'YourName', 'MemNumber')->where('DeleteMark', '1')->where('MemNumber', $memid)->first();
        return $entMemberInfo;
    }

}
